from typing import Optional, List, Tuple
from tortoise.expressions import Q
from app.models.models import Honor, HonorType

class HonorCRUD:
    @staticmethod
    async def get_by_id(honor_id: int) -> Optional[Honor]:
        """根据ID获取荣誉"""
        return await Honor.filter(id=honor_id, is_deleted=False).prefetch_related("student", "course").first()

    @staticmethod
    async def create(honor_data) -> Honor:
        """创建荣誉"""
        honor_dict = honor_data.model_dump()
        honor = await Honor.create(**honor_dict)
        await honor.fetch_related("student", "course")
        return honor

    @staticmethod
    async def update(honor_id: int, honor_data) -> Optional[Honor]:
        """更新荣誉信息"""
        honor = await Honor.filter(id=honor_id, is_deleted=False).prefetch_related("student", "course").first()
        if not honor:
            return None

        update_data = honor_data.model_dump(exclude_unset=True)
        if update_data:
            await Honor.filter(id=honor_id, is_deleted=False).update(**update_data)
            honor = await Honor.filter(id=honor_id, is_deleted=False).prefetch_related("student", "course").first()

        return honor

    @staticmethod
    async def delete(honor_id: int) -> bool:
        """删除荣誉（软删除）"""
        honor = await Honor.get_or_none(id=honor_id, is_deleted=False)
        if not honor:
            return False
        honor.is_deleted = True
        await honor.save(update_fields=["is_deleted", "updated_at"])
        return True

    @staticmethod
    async def get_list(
        skip: int = 0,
        limit: int = 20,
        search: Optional[str] = None,
        student_id: Optional[int] = None,
        type: Optional[HonorType] = None
    ) -> Tuple[List[Honor], int]:
        """获取荣誉列表"""
        query = Honor.filter(is_deleted=False).prefetch_related("student", "course")

        if search:
            query = query.filter(
                Q(name__icontains=search, is_deleted=False) |
                Q(student__name__icontains=search, is_deleted=False) |
                Q(student__student_id__icontains=search, is_deleted=False)
            )

        if student_id is not None:
            query = query.filter(student__id=student_id)

        if type is not None:
            query = query.filter(type=type, is_deleted=False)

        total = await query.count()
        honors = await query.offset(skip).limit(limit).order_by("-created_at")

        return honors, total

honor_crud = HonorCRUD()